<template>
  <el-dialog
      :title="!dataForm.id ? '新增用户' : '修改用户'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="onDialogClose"
  >
    <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="120px"
    >

      <el-form-item label="用户姓名" prop="name">
        <el-input v-model="dataForm.name" placeholder="用户姓名"></el-input>
      </el-form-item>

      <el-form-item label="头像" prop="avatar">
        <file-upload
            tip="点击上传头像"
            action="/api/upload/uploadAvatar"
            :limit="1"
            @change="avatarUploadChange"
            :fileUrls="dataForm.avatar ? dataForm.avatar:''"
        ></file-upload>
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="dataForm.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,

      dataForm: {
        id: 0,
        name: "",
        avatar: "",
        gender: "",
      },
      // 【修改点】更新验证规则
      dataRule: {
        username: [
          { required: true, message: "用户账号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "用户姓名不能为空", trigger: "blur" }
        ],
      }
    };
  },
  methods: {
    init(id) {
      this.dataForm.id = id;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: `user/info/${this.dataForm.id}`,
            method: "get"
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.data;
            }
          });
        }
      });
    },
    avatarUploadChange(file) {
      if (!file) {
        this.dataForm.avatar = "";
        return;
      }

      if (file instanceof File) {

        const formData = new FormData();
        formData.append("file", file);

        this.$http({
          url: "/api/upload/uploadAvatar",
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        }).then(({ data }) => {
          if (data.code === 0) {
            this.dataForm.avatar = data.url;
            this.$message.success("头像上传成功");
          } else {
            this.$message.error(data.msg || "上传失败");
          }
        }).catch(() => {
          this.$message.error("上传失败");
        });
      } else if (typeof file === "string") {

        this.dataForm.avatar = file;
      } else if (file?.response?.code === 0) {

        this.dataForm.avatar = file.response.url;
      } else {
        this.$message.error("头像上传失败");
      }
    },

    dataFormSubmit() {
      if(!this.dataForm.id) {
        this.$message.error("未选择用户，无法提交");
        return;
      }
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: `user/${!this.dataForm.id ? "save" : "update"}`,
            method: "post",
            data: this.dataForm
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
       onDialogClose() {
    this.$emit("dialogClosed"); 
  },
  }
};
</script>